<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="500px"
    @close="handleClose"
    destroy-on-close
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="上一级" prop="parentId">
        <section-parent-select v-model="form.parentId" :course-id="form.courseId"/>
      </el-form-item>

      <el-form-item label="章节名称" prop="sectionName">
        <el-input v-model="form.sectionName" placeholder="请输入章节名称"
         @keyup.enter.native="handleSubmit" clearable></el-input>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/common/api';
import SectionParentSelect from '@/components/admin/SectionParentSelect.vue';

export default {
  name: 'SectionDialog',
  components: {
    SectionParentSelect
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      form: {
        parentId: 0,
        sectionName: '',
        sortOrder: 0
      },
      rules: {
        sectionName: [
          { required: true, message: '请输入章节名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.form.id ? '编辑章节' : '添加章节'
    }
  },
  methods: {
    async open(data) { 
      this.form = Object.assign({}, data)
      this.dialogVisible = true
    },
    handleClose() {
      this.$refs.form.resetFields()
      this.dialogVisible = false
      this.$emit('close')
    },
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            this.loading = true
            const {data} = await api.admin_saveCourseSection(this.form)
            this.$message.success('保存成功')

            this.$emit('success', data.data)
            this.handleClose()
          } finally {
            this.loading = false
          }
        }
      })
    }, 
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
